{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "给定一个包含非负整数的 _m_ x _n_ 网格，请找出一条从左上角到右下角的路径，使得路径上的数字总和为最小。\n",
    "\n",
    "**说明：**每次只能向下或者向右移动一步。\n",
    "\n",
    "**示例:**\n",
    "\n",
    "<pre>\n",
    "**输入:**\n",
    "[\n",
    "  [1,3,1],\n",
    "  [1,5,1],\n",
    "  [4,2,1]\n",
    "]\n",
    "**输出:** 7\n",
    "**解释:** 因为路径 1→3→1→1→1 的总和最小。\n",
    "</pre>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "定义一个同样的二维数组dp[i][j]表示到这个点的最短距离\n",
    "\n",
    "公式： dp[i][j] = min(dp[i][j-1], dp[i-1][j]) + grid[i][j]\n",
    "\n",
    "超出边界的情况需要特殊处理\n",
    "\n",
    "初始值：dp[0][0] = grid[0][0]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Solution:\n",
    "    def minPathSum(self, grid: List[List[int]]) -> int:\n",
    "        if not grid:\n",
    "            return 0\n",
    "        m = len(grid)\n",
    "        n = len(grid[0])\n",
    "        if n == 0:\n",
    "            return 0\n",
    "\n",
    "        dp = [[0] * n for i in range(m)]\n",
    "        dp[0][0] = grid[0][0]\n",
    "        print(dp)\n",
    "        for i in range(m):\n",
    "            for j in range(n):\n",
    "                if j == 0 and i == 0:\n",
    "                    continue\n",
    "                if i == 0:  # 处理第一排\n",
    "                    print(i, j, dp[i][j])\n",
    "                    dp[i][j] = dp[i][j-1] + grid[i][j]\n",
    "                elif j == 0:\n",
    "                    dp[i][j] = dp[i-1][j] + grid[i][j]\n",
    "                else:\n",
    "                    dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j]\n",
    "        return dp[m-1][n-1]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "看视频的时候，讲师提出一个问题，题目规定非负整数的意义，如果有负数会发生什么？\n",
    "\n",
    "我试了一下，并没有发生任何情况，还是能运行。。。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
